#include <database\mysqlDatabase.h>

bool 
mysqlDatabase::connect(string host="tcp://127.0.0.1:3306", string user="root", string pass="root") {
  try {
    driver = get_driver_instance();
      con = driver->connect(host, user, pass);
      return true;
  }
  catch (SQLException &e) {
    #ifdef DEBUG_INFO
    cerr << "ERROR: " << e.what();
	  cerr << " (MySQL error code: " << e.getErrorCode();
		cerr << ", SQLState: " << e.getSQLState() << ")" << endl;
    #endif
		return false;
  }
}

sql::PreparedStatement *
mysqlDatabase::prepareQuery(std::string query) {
  return con->prepareStatement(query.c_str());
}

bool
mysqlDatabase::executequery(std::string query) {
  if (connected()) {
    try {
      std::auto_ptr<sql::Statement> stmt(con->createStatement());
      stmt->executeUpdate(query);
      cerr << "Query ok: '" << query << "'" << endl;
      return true;
    }
    catch (SQLException &e) {
      #ifdef DEBUG_INFO
		  cerr << "ERROR: " << e.what();
		  cerr << " (MySQL error code: " << e.getErrorCode();
		  cerr << ", SQLState: " << e.getSQLState() << ")" << endl;
      #endif
    }
  }
  else {
    cerr << "No connection to db" << endl;
  }
  return false;
}

ResultSet *
mysqlDatabase::sendquery(std::string query) {
  if (connected()) {
    try {
      std::auto_ptr<sql::Statement> stmt(con->createStatement());
      stmt->execute(query);
      #ifdef DEBUG_INFO
      cout << "Query ok: '" << query << "'" << endl;
      #endif
      return stmt->getResultSet();
    }
    catch (SQLException &e) {
      #ifdef DEBUG_INFO
		  cerr << "ERROR: " << e.what();
		  cerr << " (MySQL error code: " << e.getErrorCode();
		  cerr << ", SQLState: " << e.getSQLState() << ")" << endl;
      #endif
    }
  }
  else {
    cerr << "No connection to db" << endl;
  }

  return NULL;
}

bool 
mysqlDatabase::connected(void) const {
  return con != NULL;
}

void
mysqlDatabase::closeConnection() {
  if (con) {
    con->close();
    delete con;
    con = NULL;
  }
}

mysqlDatabase::mysqlDatabase() {
  driver = NULL;
  con = NULL;
}

mysqlDatabase::~mysqlDatabase() {
  clear();
}

void 
mysqlDatabase::clear() {
	if (con) con->close();
	if (con) delete con;
  con = NULL;
};